<template>
  <div class="upload-container">
    <div class="upload-content">
      <el-card class="upload-card">
        <template #header>
          <div class="card-header">
            <h2>上传视频</h2>
          </div>
        </template>

        <el-form :model="form" label-width="80px">
          <el-form-item label="视频文件" required>
            <el-upload
              class="video-uploader"
              :action="uploadUrl"
              :headers="headers"
              :before-upload="beforeUpload"
              :on-progress="onProgress"
              :on-success="onSuccess"
              :on-error="onError"
              accept=".mp4,.mov,.avi"
              :auto-upload="false"
              ref="uploadRef"
            >
              <template #trigger>
                <div class="upload-trigger">
                  <el-icon class="upload-icon"><Upload /></el-icon>
                  <div class="upload-text">点击或拖拽视频文件到此处上传</div>
                  <div class="upload-tip">支持 mp4、mov、avi 格式，最大 500MB</div>
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="视频标题" required>
            <el-input v-model="form.title" placeholder="请输入视频标题" />
          </el-form-item>

          <el-form-item label="视频描述">
            <el-input
              v-model="form.description"
              type="textarea"
              rows="4"
              placeholder="请输入视频描述"
            />
          </el-form-item>

          <el-form-item label="视频标签">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              placeholder="请选择标签"
            >
              <el-option
                v-for="tag in tags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="是否公开">
            <el-switch v-model="form.isPublic" />
          </el-form-item>

          <div class="upload-progress" v-if="uploadProgress > 0">
            <el-progress :percentage="uploadProgress" />
          </div>

          <el-form-item>
            <el-button type="primary" @click="submitUpload" :loading="uploading">
              开始上传
            </el-button>
            <el-button @click="$router.push('/')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { tagApi } from '@/api/tag'

const router = useRouter()
const uploadRef = ref(null)
const uploadProgress = ref(0)
const uploading = ref(false)
const tags = ref([])

const form = ref({
  title: '',
  description: '',
  tags: [],
  isPublic: true,
  duration: 0
})

// 上传相关配置
const uploadUrl = import.meta.env.VITE_API_URL + '/api/videos/upload'
const headers = computed(() => ({
  Authorization: 'Bearer ' + localStorage.getItem('token')
}))

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await tagApi.getTagList()
    if (res.code === 1) {
      tags.value = res.data
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 上传前验证
const beforeUpload = async (file) => {
  const isVideo = /\.(mp4|mov|avi)$/i.test(file.name)
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 500MB!')
    return false
  }

  try {
    // 获取视频时长
    const duration = await getVideoDuration(file)
    // 将时长添加到表单数据中
    form.value.duration = duration
    return true
  } catch (error) {
    console.error('获取视频时长失败:', error)
    return false
  }
}

// 上传进度
const onProgress = (event) => {
  uploadProgress.value = Math.round(event.percent)
}

// 上传成功
const onSuccess = (response) => {
  uploading.value = false
  if (response.code === 1) {
    ElMessage.success('视频上传成功')
    router.push('/')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败
const onError = () => {
  uploading.value = false
  ElMessage.error('上传失败，请重试')
}

// 提交上传
const submitUpload = async () => {
  if (!form.value.title.trim()) {
    ElMessage.warning('请输入视频标题')
    return
  }
  
  // 获取上传文件
  const uploadFile = uploadRef.value.uploadFiles[0]
  if (!uploadFile) {
    ElMessage.warning('请选择要上传的视频')
    return
  }

  uploading.value = true
  
  // 创建FormData
  const formData = new FormData()
  formData.append('file', uploadFile.raw)
  formData.append('title', form.value.title)
  formData.append('description', form.value.description)
  formData.append('isPublic', form.value.isPublic)
  formData.append('duration', form.value.duration)
  if (form.value.tags.length > 0) {
    formData.append('tags', JSON.stringify(form.value.tags))
  }

  // 手动上传
  uploadRef.value.submit()
}

// 组件挂载时获取标签列表
onMounted(() => {
  fetchTags()
})

const getVideoDuration = (file) => {
  return new Promise((resolve) => {
    const video = document.createElement('video')
    video.preload = 'metadata'
    video.src = URL.createObjectURL(file)
    
    video.onloadedmetadata = () => {
      URL.revokeObjectURL(video.src)
      resolve(video.duration)
    }
  })
}

const handleUpload = async (file) => {
  try {
    // 获取视频时长
    const duration = await getVideoDuration(file)
    
    // 创建表单数据
    const formData = new FormData()
    formData.append('file', file)
    formData.append('duration', duration)
    
    // 上传视频
    const res = await videoApi.uploadVideo(formData)
    // ...处理上传响应
  } catch (error) {
    ElMessage.error('上传失败')
  }
}
</script>

<style scoped>
.upload-container {
  padding: 24px;
  min-height: calc(100vh - 64px);
  background: var(--bg-secondary);
  margin-top: 64px;
}

.upload-content {
  max-width: 800px;
  margin: 0 auto;
}

.upload-card {
  background: var(--bg-primary);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 var(--shadow-color);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--text-primary);
}

.video-uploader {
  width: 100%;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-trigger:hover {
  border-color: #409EFF;
  background: var(--hover-bg);
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: var(--text-secondary);
}

.upload-progress {
  margin: 20px 0;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style> 